package dao

import (
	"fmt"
	"log"
	"superstar/models"
	"xorm.io/xorm"
)

type SuperstarDao struct {
	engine *xorm.Engine
}

// 实例化操作类
func NewSuperstartDao(engine *xorm.Engine) *SuperstarDao {
	return &SuperstarDao{
		engine: engine,
	}
}

func (d SuperstarDao) Get(id int) *models.StarInfo {
	data := &models.StarInfo{Id: id}
	ok, err := d.engine.Get(data)
	fmt.Println(ok)

	if ok && err == nil {
		return data
	} else {
		// return nil

		data.Id = 0
		return data
	}
}

func (d SuperstarDao) GetAll() []models.StarInfo {
	// datalist := make([]models.StarInfo, 0)
	datalist := []models.StarInfo{}
	err := d.engine.Desc("id").Find(&datalist)

	if err != nil {
		log.Println(err)
		return nil
	} else {
		return datalist
	}
}

func (d SuperstarDao) Search(country string) []models.StarInfo {
	// datalist := make([]models.StarInfo, 0)
	datalist := []models.StarInfo{}
	err := d.engine.Where("country=?", country).Desc("id").Find(&datalist)

	if err != nil {
		log.Println(err)
		return nil
	} else {
		return datalist
	}
}

func (d SuperstarDao) DeleteByID(id int) error {
	data := &models.StarInfo{Id: id, SysStatus: 1}
	_, err := d.engine.ID(id).Update(data)

	return err
}

func (d SuperstarDao) Update(data *models.StarInfo, columns []string) error {
	_, err := d.engine.MustCols(columns...).ID(data.Id).Update(data)

	return err
}

func (d SuperstarDao) Create(data *models.StarInfo) error {
	_, err := d.engine.Insert(data)

	return err
}
